import utils from '../core/utils';
import request from '@ohos.request';
import logger from '../core/logger';
import installer from '../core/installer';
import settingHelper from './settingHelper';
import downloadManager from './downloadManager';
import { appInfo } from '../models/apis/appInfo';
import { taskStatus } from '../models/enums/taskStatus';
import { downloadInfo } from '../models/manage/downloadInfo';

class downloader {
  private _tasks: Map<number, request.DownloadTask>;

  constructor() {
    this._tasks = new Map<number, request.DownloadTask>();
  }

  start(url: string, zipFilePath: string, app: appInfo): Promise<number> {
    return new Promise((resolve) => {
      let id = 0;
      try {
        request.downloadFile(globalThis.abilityContext, {
          url: url,
          background: true,
          filePath: zipFilePath
        }).then((data) => {
          data.getTaskInfo().then((res) => {
            id = res.downloadId;
            this.save(id, 0, app, zipFilePath);
            this._tasks.set(res.downloadId, data);
          });
          data.on('complete', () => {
            this.save(id, taskStatus.success, app, zipFilePath);
            if (settingHelper.autoInstall) {
              installer.install(zipFilePath).then((res) => {
                let status = utils.isEmpty(res) ? taskStatus.install : taskStatus.failed;
                this.save(id, status, app, zipFilePath);
                resolve(utils.isEmpty(res) ? 1 : 0);
              });
            } else {
              utils.showPopup('下載完成！');
              resolve(0);
            }
          });
          data.on('fail', (err) => {
            this.save(id, taskStatus.error, app, zipFilePath);
            logger.error(err);
            utils.showPopup('下载失败');
            resolve(0);
          });
        }).catch((err) => {
          this.save(id, taskStatus.error, app, zipFilePath);
          logger.error(err);
          utils.showPopup('下载失败');
          resolve(0);
        });
      } catch (err) {
        this.save(id, taskStatus.error, app, zipFilePath);
        logger.error(err);
        utils.showPopup('下载失败');
        resolve(0);
      }
    });
  }

  pause(id: number) {
    let info = this._tasks.get(id);
    if (!utils.isEmpty(info)) {
      this.save(id, taskStatus.pause);
      info.suspend();
    }
  }

  resume(id: number) {
    let info = this._tasks.get(id);
    if (!utils.isEmpty(info)) {
      this.save(id, taskStatus.running);
      info.restore();
    }
  }

  async delete(id: number): Promise<void> {
    let info = this._tasks.get(id);
    await downloadManager.instance.delete(id);
    if (!utils.isEmpty(info))
      info.delete();
  }

  getTask(downloadId: number) {
    return this._tasks.get(downloadId);
  }

  getDownloadList(): Promise<Array<downloadInfo>> {
    return downloadManager.instance.getAllData();
  }

  private save(id: number, status: taskStatus, app?: appInfo, filePath?: string) {
    var item = new downloadInfo(id, app, filePath);
    item.status = status;
    downloadManager.instance.saveData(item);
  }
}
export default new downloader();